﻿using LEDStripMixer.Shared.Constants;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LEDStripMixer
{
    public class ArduinoEntryPoint
    {
        #region Properties

        private static SerialPort arduino = new SerialPort();

        public static SerialPort Instance
        {
            get
            {
                return arduino;
            }
        }

        public static List<String> COMPorts { get { return SerialPort.GetPortNames().ToList(); } }

        #endregion

        #region Constructors

        private ArduinoEntryPoint()
        {
            arduino.Handshake = System.IO.Ports.Handshake.None;
            arduino.Parity = Parity.None;
            arduino.DataBits = 8;
            arduino.StopBits = StopBits.One;
            arduino.ReadTimeout = 500;
            arduino.WriteTimeout = 500;
            arduino.Encoding = System.Text.Encoding.ASCII;
        }

        #endregion

        #region Public Methods

        public static void Configure(Int32 baudRate, string COMPort)
        {
            arduino.BaudRate = baudRate;
            arduino.PortName = COMPort;
        }

        public static void SendData(string data) 
        {
            if (!COMPorts.Contains(arduino.PortName)) ResolveCOMPort();

            if (!arduino.IsOpen) arduino.Open(); 

            var frameBuffer = data.Split(FrameConstants.FRAME_END);

            foreach (var frame in frameBuffer)
            {
                arduino.Write(frame + FrameConstants.FRAME_END);
            }

            Stop();
        }

        public static void Stop()
        {
            arduino.Close();
        }

        private static void ResolveCOMPort() {
            try
            {
                arduino.PortName = COMPorts.First();
            }
            catch { }
        }

        #endregion
    }
}
